#include "tmrobotctrl.h"
#include "tmglobaldef.h"


TMRobotCallBackCtrl::TMRobotCallBackCtrl()
{

}

bool TMRobotCallBackCtrl::install(const NetWorkRobot::CallBackPrx &callBack, const std::string &robotInfo, const Ice::Current &)
{
    QString strRobotInfo = QString(QString::fromUtf8(robotInfo.c_str()));
    QJsonParseError json_error;
    QJsonDocument jsDoc = QJsonDocument::fromJson(strRobotInfo.toUtf8(), &json_error);
    if(json_error.error != QJsonParseError::NoError)
    {
        g_pLog->log_E("json parse error,install robot error!");
        return false;
    }

    QJsonObject jsObj = jsDoc.object();

    QString strRobotMac = jsObj.value("robotMac").toString();
    QString strPwd = jsObj.value("password").toString();
    QString strSN = jsObj.value("sn").toString();
    QString strVersion = jsObj.value("version").toString();
    QString strAVadress = jsObj.value("AVadress").toString();

    if(strRobotMac.size() > 0 && pMySqlCtrl->robotIsInMySQL(strRobotMac)){
        robotMap.insert(strRobotMac,callBack);
        pMySqlCtrl->saveRobotInfo(strRobotMac,strPwd,strSN,strVersion,TMMySQLCtrl::ONLINE,strAVadress);
        g_pLog->log_D(QString("robot %1 install success!").arg(strRobotMac));
        g_pLog->log_D(QString("robotMap size: %1").arg(robotMap.size()));
        return true;
    }
    g_pLog->log_D(QString("robot %1 install failed!").arg(strRobotMac));
    return false;
}

bool TMRobotCallBackCtrl::unInstall(const std::string &strMac,const Ice::Current &)
{
    if(!strMac.empty() && robotMap.contains(stdToQString(strMac))){
        robotMap.remove(stdToQString(strMac));
        pMySqlCtrl->updateRobotState(stdToQString(strMac),TMMySQLCtrl::OFFLINE);
        g_pLog->log_D(QString("robot %1 uninstall success!").arg(stdToQString(strMac)));
        g_pLog->log_D(QString("robotMap size: %1").arg(robotMap.size()));
        return true;
    }
    g_pLog->log_D(QString("robot %1 uninstall failed!").arg(stdToQString(strMac)));
    return false;
}
